<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Hash;

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'password','name', 'email',"phone","type",'sex',"photo"
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token'
    ];  

    //已经计划好的代码部分的任务 完成度



    public function login(Request $request){

        $data=$request->only('name','password','code','code_key');

        if (!captcha_api_check($data['code'], $data['code_key'])){

            return ThrowApiExc('100');
            //
        }



        $user=DB::table('users')->where('name',$data['name'])->first();
        DB::table("users")->where("id",$user['id'])->update(['last_login'=>date("Y-m-d H:i:s",time())]);
        if(!$user) return ThrowApiExc('101');

        if(!Hash::check($data['password'],$user['password'])) return ThrowApiExc('102');


        $token  =   sha1(microtime().$user['name'].$data['code'].env('APP_KEY'));

        $ttl = 3 * 86400;  //过期时间 N *  天
        Redis::setex("code:".$token,$ttl,$user['id']);

        Redis::del($request->verfiy_uuid); //删除验证码


        return [
            'status_code'      => 200,
            'message'     =>  '请求成功',
            'data' => [
                'token'=>$token,
                'expires_in'=>$ttl
            ]
        ];

    }


    public function aladdin_login(Request $request){
        $data=$request->only('token','useridno');

        if(!array_key_exists('token',$data)) return ThrowApiExc('401');


        $user=DB::connection('mysql2')->table('users')->where('useridno',$data['useridno'])->first();

        if(!$user){
            return [
                'status_code'      => 408,
                'message'     =>  '请求失败',
                'data' => "sop无此用户"
            ];
        }
        
        $token  =   sha1(microtime().$user['name'].env('APP_KEY'));
        $ttl = 3 * 86400;  //过期时间 N *  天
        Redis::setex("code:".$token,$ttl,$user['id']);

        return [
            'status_code'      => 200,
            'message'     =>  '请求成功',
            'data' => [
                'token'=>$token,
                'expires_in'=>$ttl
            ]
        ];
    }



    public function demo(){
        Redis::set("demo:hhl",'1');
        $res = Redis::get("demo:hhl");
        Redis::set("demo:hhl",'');
        return $res;
    }


    




}
